﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BusStopsRouteHistory.aspx.cs" Inherits="GPSTrackingWebsiteManager.Pages.BusStopsRouteHistory" %>

<!DOCTYPE html>
<link href="../Css/GPSTrackingWebsite.css" rel="stylesheet" />
<script src="../Javascript/WindowMessageManager.js"></script>
<script src="../Javascript/ObjectsV2.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Historial de Paradas de Buses</title>
</head>   
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
    <script type="text/javascript">
    
        var opener = GetRadWindow();
        var Routes = new Routes();
        var Companies = new Companies();
        var VPCProcesses = new VPCProcesses();
        var BusStopsManager = new BusStopsManager();

        var firstRouteHasGPSPoints = true;

        function GetRadWindow() {
            var oWindow = null;
            if (window.radWindow)
                oWindow = window.radWindow;
            else if (window.frameElement.radWindow)
                oWindow = window.frameElement.radWindow;
            return oWindow.BrowserWindow;
        }

        function getCompaniesByAdminUsername() {
            requestStart(getrpvRoutesUpdateControl());
            PageMethods.wsGetCompaniesByAdminUsername(getCompaniesByAdminUsernameOk, getCompaniesByAdminUsernameError);
        }

        //Utilizada
        function getrpvPlayerUpdateControl() {
            return "<%=  rpvPlayer.ClientID %>";
        }

        //Utilizada
        function getrpvRoutesUpdateControl() {
            return "<%=  rpvRoutes.ClientID %>";
        }

        //Utilizada
        function getCompaniesByAdminUsernameOk(object) {
            Companies.openXMLCompaniesByAdminUsername(object, opener.globalBusStopsRouteHistory.companiesList);
            Companies.loadCompaniesDataSource(getCompaniesGrid(), opener.globalBusStopsRouteHistory.companiesList, opener.globalBusStopsRouteHistory.companiesDataSource);
            if (opener.globalBusStopsRouteHistory.companiesList.length == 1) {
                getCompaniesGrid().selectItem(0);
                opener.globalBusStopsRouteHistory.companyIDSelected = opener.globalBusStopsRouteHistory.companiesList[0].companyID;
                responseEnd(getrpvRoutesUpdateControl());
                //if (GeoFences.isValidToGetGeoFences(getGeoFenceGrid(), opener.globalGeoFences.companyID, opener.globalGeoFences.companiesList[0].companyID, opener.globalGeoFences.geoFencesList, opener.globalGeoFences.companiesList, opener.globalGeoFences.geoFencesDataSource)) {
                    //requestStart(getrpvClientManagerUpdateControl());
                //    opener.globalGeoFences.companyID = opener.globalGeoFences.companiesList[0].companyID;
                //    getGeoFencesByCompanyID();
                //}
            }
            else {
                responseEnd(getrpvRoutesUpdateControl());
            }
        }

        //Utilizada
        function getCompaniesByAdminUsernameError(error) {
            responseEnd(getrpvRoutesUpdateControl());
            msgError(error.get_message(), titles.clientTitle);
        }

        //Utilizada
        function getCompaniesGrid() {
            try {
                return $find("<%= rgCompaniesGrid.ClientID %>").get_masterTableView();
            }
            catch (ex) {
                setTimeout(getCompaniesGrid, 100);
            }
        }

        //Utilizada
        function getVPCProcessGrid() {
            try {
                return $find("<%= VPCProcessGrid.ClientID %>").get_masterTableView();
            }
            catch (ex) {
                setTimeout(getVPCProcessGrid, 100);
            }
        }

        
        //Utilizada
        function CompaniesGrid_OnRowClick(sender, args) {
            VPCProcesses.clearBusRoutes(opener);
            //if (GeoFences.isValidToGetGeoFences(getGeoFenceGrid(), opener.globalGeoFences.companyID, args.getDataKeyValue("CompanyID"), opener.globalGeoFences.geoFencesList, opener.globalGeoFences.companiesList, opener.globalGeoFences.geoFencesDataSource)) {
                //requestStart(getrpvRoutesUpdateControl());
                opener.globalBusStopsRouteHistory.companyIDSelected = args.getDataKeyValue("CompanyID");
                //opener.globalBusStopsRouteHistory.busRouteIDSelected = args.getDataKeyValue("BusRouteID");
                if (opener.globalBusStopsRouteHistory.dateSelected != null && opener.globalBusStopsRouteHistory.companyIDSelected != null) {
                    requestStart(getrpvRoutesUpdateControl());
                    PageMethods.wsGetVPCProcessByDatesByCompanyID(opener.globalBusStopsRouteHistory.dateSelected, opener.globalBusStopsRouteHistory.companyIDSelected, getVPCProcessByDateByCompanyIDOk, getVPCProcessByDateByCompanyIDError);
                }

            //getGeoFencesByCompanyID();
            //}
        }

        //Utilizada
        function VPCProcessGrid_OnRowClick(sender, args) {
            VPCProcesses.clearBusRoutes(opener);
            opener.globalBusStopsRouteHistory.busRouteIDSelected = args.getDataKeyValue("BusRouteID");
            opener.globalBusStopsRouteHistory.numControlSelected = args.getDataKeyValue("NumControl");
            getBusStopsByCompanyIDAndBusRouteID();
        }

        //Utilizada
        function getBusStopsByCompanyIDAndBusRouteID() {
            if (opener.globalBusStopsRouteHistory.companyIDSelected != null && opener.globalBusStopsRouteHistory.busRouteIDSelected != null && opener.globalBusStopsRouteHistory.companyIDSelected != -1 && opener.globalBusStopsRouteHistory.busRouteIDSelected != -1) {
                requestStart(getrpvRoutesUpdateControl());
                PageMethods.wsGetBusStopsByCompanyIDAndBusRouteID(opener.globalBusStopsRouteHistory.companyIDSelected, opener.globalBusStopsRouteHistory.busRouteIDSelected, getBusStopsByCompanyIDAndBusRouteIDOk, getBusStopsByCompanyIDAndBusRouteIDError);
            }
        }

        //Utilizada
        function getBusStopsByCompanyIDAndBusRouteIDOk(object) {
            BusStopsManager.openXMLBusStopsByCompanyAndBusRouteID(opener.objMapControl, object, opener.globalBusStopsRouteHistory.busStopsList);
            //BusStopsManager.loadBusStopDataSource(getVPCProcessGrid(), opener.globalBusStopsManager.busStopsList, opener.globalBusStopsManager.busStopsDataSource);
            GetAllBusRouteDetailsByBusRouteID();
            for (i = 0; i < opener.globalBusStopsRouteHistory.busStopsList.length; i++) {
                //getVPCProcessGrid().selectItem(i);

                opener.globalBusStopsRouteHistory.busStopsList[i].checked = true;
                if (getCkbCenterBusStops().checked) {
                    opener.objMapControl.centerMap(opener.objMapControl.getPositionMarker(opener.globalBusStopsRouteHistory.busStopsList[i].marker));
                }

                if (getCkbZoomBusStops().checked) {
                    opener.objMapControl.zoomMap(16);
                }
                
            }
            BusStopsManager.showAllBusStopsChecked(opener.globalBusStopsRouteHistory.busStopsList);
            loadRouteHistory();
            //responseEnd(getrpvRoutesUpdateControl());
        }

        function GetAllBusRouteDetailsByBusRouteID() {
            PageMethods.wsGetAllBusRouteDetailsByBusRouteID(opener.globalBusStopsRouteHistory.busRouteIDSelected, GetAllBusRouteDetailsByBusRouteIDOk, GetAllBusRouteDetailsByBusRouteIDError);
        }

        //Utilizada
        function GetAllBusRouteDetailsByBusRouteIDOk(object) {
            //VPCProcesses.clearBusRoutes(opener);
            BusStopsManager.openXMLBusRouteDetailsByBusRouteID(object, opener.globalBusStopsRouteHistory);

            opener.globalBusStopsRouteHistory.temporalyIndex = 0;
            opener.globalBusStopsRouteHistory.temporalyInterval = setInterval(function () { loadBusRouteDisplay(opener); }, opener.globalBusStopsRouteHistory.timeToCalculateRoute);
        }

        //Utilizada
        function loadBusRouteDisplay(opener) {
            if (opener.globalBusStopsRouteHistory.temporalyIndex < opener.globalBusStopsRouteHistory.temporalyList.length) {
                opener.objMapControl.addBusRouteHistoryClickDB(opener.globalBusStopsRouteHistory.temporalyList[opener.globalBusStopsRouteHistory.temporalyIndex++]);
            }
            else {
                clearInterval(opener.globalBusStopsRouteHistory.temporalyInterval);
                responseEnd(getrpvRoutesUpdateControl());
            }
        }

        //Utilizada
        function GetAllBusRouteDetailsByBusRouteIDError(error) {
            responseEnd(getrpvBusStopsManagerUpdateControl());
            msgError(error.get_message(), titles.busStopsTitle);
        }

        //Utilizada
        function getBusStopsByCompanyIDAndBusRouteIDError(error) {
            responseEnd(getrpvRoutesUpdateControl());
            msgError(error.get_message(), titles.busStopsTitle);
        }
        

        //Utilizada
        function getVPCProcessByDateByCompanyID(sender, eventArgs) {
            if (sender != null) {
                if (eventArgs.get_renderDay().get_isSelected()) {
                    VPCProcesses.clearBusRoutes(opener);
                    opener.globalBusStopsRouteHistory.dateSelected = sender.DateTimeFormatInfo.FormatDate(eventArgs.get_renderDay().get_date(), "yyyy/MM/dd");
                    //var dfi = sender.DateTimeFormatInfo;
                    //var formattedDate = dfi.FormatDate(date, dfi.ShortDatePattern);
                    //alert(formattedDate + " was just " +
                    //(eventArgs.get_renderDay().get_isSelected() ? "selected. " : "unselected. "));
                    if (opener.globalBusStopsRouteHistory.dateSelected != null && opener.globalBusStopsRouteHistory.companyIDSelected != null && opener.globalBusStopsRouteHistory.companyIDSelected != -1) {
                    requestStart(getrpvRoutesUpdateControl());
                    PageMethods.wsGetVPCProcessByDatesByCompanyID(opener.globalBusStopsRouteHistory.dateSelected, opener.globalBusStopsRouteHistory.companyIDSelected, getVPCProcessByDateByCompanyIDOk, getVPCProcessByDateByCompanyIDError);
                }
                }
            }
        }

        //Utilizada
        function getVPCProcessByDateByCompanyIDOk(object) {
            VPCProcesses.openXMLVPCPocess(object, opener.globalBusStopsRouteHistory.vpcProcessList);
            VPCProcesses.loadVPCProcessDataSource(getVPCProcessGrid(), opener.globalBusStopsRouteHistory.vpcProcessList, opener.globalBusStopsRouteHistory.vpcProcessDataSource);
            
            /*if (opener.globalBusStopsRouteHistory.vpcProcessList.length == 1) {
                getVPCProcessGrid().selectItem(0);
                //if (GeoFences.isValidToGetGeoFences(getGeoFenceGrid(), opener.globalGeoFences.companyID, opener.globalGeoFences.companiesList[0].companyID, opener.globalGeoFences.geoFencesList, opener.globalGeoFences.companiesList, opener.globalGeoFences.geoFencesDataSource)) {
                //requestStart(getrpvClientManagerUpdateControl());
                //    opener.globalGeoFences.companyID = opener.globalGeoFences.companiesList[0].companyID;
                //    getGeoFencesByCompanyID();
                //}
                responseEnd(getrpvRoutesUpdateControl());
            }
            else {
                responseEnd(getrpvRoutesUpdateControl());
            }*/
            
            responseEnd(getrpvRoutesUpdateControl());
        }

        //Utilizada
        function getVPCProcessByDateByCompanyIDError(error) {
            responseEnd(getrpvRoutesUpdateControl());
            msgError(error.get_message(), titles.clientTitle);
        }

        function loadRouteHistory() {
            //if (Routes.isValidToLoadRoute(opener.globalGPSImei.imeiSelected, getDateSelected().get_textBox().value)) {
            //    requestStart(getrpvRoutesUpdateControl());
            //    Routes.enableDisableSliderRoute(false, getSliderRouter());
                //getBtnLoadRoute().disabled = true;
                getBtnPlayPause().set_enabled(false);
                //FirstSelection
                firstRouteHasGPSPoints = true;

            //oWndShow.BusStopsRouteHistory.window.width = "100px";
                

                PageMethods.wsLoadVPCRouteHistory(opener.globalBusStopsRouteHistory.numControlSelected, true, loadRouteHistoryFirstSelectionOk, loadRouteHistoryFirstSelectionError);
            //}
        }

        function loadRouteHistoryFirstSelectionOk(stringCollection) {
            if (stringCollection == "") {
                firstRouteHasGPSPoints = false;
            }
            opener.objMapControl.setPositionMarker(opener.globalBusStopsRouteHistory.GPSImeiRoute, null);
            VPCProcesses.openCollectionStringProcessDetailsFirsSelection(stringCollection, opener, opener.globalBusStopsRouteHistory);
            //alert(opener.globalBusStopsRouteHistory.trackDataByImei.length);
            getBtnPlayPause().set_enabled(true);
            
            //SecondSelection
            //PageMethods.wsLoadRouteHistory(opener.globalGPSImei.imeiSelected, getFormatDate(getDateSelected().get_textBox().value), false, loadRouteHistorySecondSelectionOk, loadRouteHistorySecondSelectionError);

            clearInterval(opener.globalBusStopsRouteHistory.refreshIntervalId);
            getBtnPlayPause().set_enabled(true);
            slider = getSliderRouter();
            slider.set_maximumValue(opener.globalBusStopsRouteHistory.trackDataByImei.length - 1);

            opener.globalBusStopsRouteHistory.currentSlideRouteNumber = 0;
            opener.objMapControl.setIconMarker(opener.globalBusStopsRouteHistory.GPSImeiRoute, opener.globalBusStopsRouteHistory.trackDataByImei[0].image);

            slider.set_value(0);
                        
            getResumenRouteHistory();

            //Routes.enableDisableSliderRoute(true, getSliderRouter());

        }

        function getResumenRouteHistory() {
            PageMethods.wsGetResumenRouteHistory(opener.globalBusStopsRouteHistory.numControlSelected, getResumenRouteHistoryOk, getResumenRouteHistoryError);
        }

        function getResumenRouteHistoryOk(resumen) {
            VPCProcesses.openXMLResumenProcessDetails(resumen, opener);
            updateCurrentPositionRouteHistory(opener.globalBusStopsRouteHistory.currentSlideRouteNumber);
            responseEnd(getrpvRoutesUpdateControl());
        }

        function getResumenRouteHistoryError(error) {
            responseEnd(getrpvBusStopsManagerUpdateControl());
            msgError(error.get_message(), titles.busStopsTitle);
        }

            function loadRouteHistorySecondSelectionOk(stringCollection) {
                if (stringCollection == "") {
                    if (!firstRouteHasGPSPoints) {
                        msgInformation("No hay rutas definidas para la fecha seleccionada.", titles.RoutesHistoryTitle);
                        getBtnLoadRoute().value = "Cargar Ruta";
                        getBtnLoadRoute().disabled = false;
                        responseEnd(getrpvRoutesUpdateControl());
                    }
                }
                else {
                    Routes.openCollectionStringTrackDataByImeiSecondSelection(stringCollection, opener);
                }

                getBtnLoadRoute().value = "Cargando... 1%";
                opener.globalRoutes.firstRoute = true;
                opener.objMapControl.routes = [];
                drawDrivingRoute(opener);
            }

            function loadRouteHistoryFirstSelectionError(error) {
                msgError(error.get_message());
                responseEnd(getrpvRoutesUpdateControl());
            }

            function loadRouteHistorySecondSelectionError(error) {
                msgError(error.get_message());
                responseEnd(getrpvRoutesUpdateControl());
            }

            function drawDrivingRoute(opener) {
                opener.globalRoutes.currentGpsPoint = 0;
                opener.globalRoutes.firstRoute = true;
                opener.objMapControl.clearStopsMarkers();
                opener.objMapControl.clearPeopleCounterMarkers();
                opener.globalRoutes.peopleTotalIn = -1;
                opener.globalRoutes.peopleTotalOut = -1;
                Routes.showHistoryRoute(opener);
                opener.globalRoutes.doesnWorkDrawRoute = false;
                opener.globalRoutes.lastOne = false;
                opener.globalRoutes.mtsRoute = opener.globalRoutes.mtsRouteStar;
                opener.globalRoutes.refreshIntervalId = setInterval(drawDrivingRouteTimer, 100);
                responseEnd(getrpvRoutesUpdateControl());
            }

            function drawDrivingRouteTimer() {

                if (opener.globalBusStopsRouteHistory.trackDataByImei.length > 1) {
                    var lstart = 0;

                    var existsMarker = false;
                    var stopTimes = 0;
                    var initialStop = 0;

                    for (opener.globalRoutes.currentGpsPoint = opener.globalRoutes.currentGpsPoint; opener.globalRoutes.currentGpsPoint < opener.globalBusStopsRouteHistory.trackDataByImei.length - 2; opener.globalRoutes.currentGpsPoint++) {
                        getBtnLoadRoute().value = "Cargando..." + formatTwoDecimals((opener.globalRoutes.currentGpsPoint / opener.globalBusStopsRouteHistory.trackDataByImei.length) * 100) + "%";


                        /*if (opener.globalRoutes.peopleTotalIn == -1 && opener.globalRoutes.peopleTotalOut == -1) {
                            opener.globalRoutes.peopleTotalIn = opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalIn;
                            opener.globalRoutes.peopleTotalOut = opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut;
                        }*/
                    
                        if (opener.globalRoutes.peopleTotalIn != opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalIn || opener.globalRoutes.peopleTotalOut != opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut) {// && (opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalIn == opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].peopleTotalIn))){// || (opener.globalRoutes.peopleTotalOut != opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut && opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut == opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].peopleTotalOut)) {
                            var myPeopleCounterMarker = new PeopleCounterMarker();

                            myPeopleCounterMarker.setPeopleCounterMarker(opener.objMapControl.addPeopleCounterMarker(images.locationPeopleCounter, opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].position, ""), opener.objMapControl.addInfoWindow(), opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleIn, opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleOut, opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalInside, opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalIn, opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut);

                            //if (!getCkbSiNoShowStops().checked) {
                            //    myStopMarker.stopMarker.setVisible(false);
                            //}

                            opener.globalList.peopleCounterMarkers.push(myPeopleCounterMarker);

                            opener.globalRoutes.peopleTotalIn = opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalIn;
                            opener.globalRoutes.peopleTotalOut = opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].peopleTotalOut;
                        }
                    
                    







                        if (lstart == 0) {
                            if (opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].currentKm - opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].currentKm >= opener.globalRoutes.mtsRoute) {
                                if (opener.globalRoutes.doesnWorkDrawRoute) {
                                    opener.globalRoutes.doesnWorkDrawRoute = false;
                                    lstart = 0;
                                    opener.globalRoutes.destination = opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].position;
                                    opener.objMapControl.getDrivingRoute();
                                    return;
                                }
                                else {
                                    lstart = 1;
                                    opener.globalRoutes.origin = opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].position;
                                    if (opener.globalList.stopsMarkers.length > 0 && opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop == null) {
                                        opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop = opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].hour;
                                    }
                                }
                            }
                            else {
                                if (opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].currentKm - opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].currentKm < opener.globalRoutes.mtsStop) {
                                    if (!existsMarker) {
                                        if (initialStop == 0) {
                                            initialStop = opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].hour;
                                        }
                                        if (stopTimes > opener.globalRoutes.timesStop) {

                                            var myStopMarker = new StopMarker();

                                            myStopMarker.setStopMarker(opener.objMapControl.addStopMarker(images.locationStop, opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].position, ""), opener.objMapControl.addInfoWindow(), initialStop);

                                            if (!getCkbSiNoShowStops().checked) {
                                                myStopMarker.stopMarker.setVisible(false);
                                            }

                                            opener.globalList.stopsMarkers.push(myStopMarker);

                                            existsMarker = true;
                                        }
                                        else {
                                            stopTimes++;
                                        }
                                    }
                                    else {
                                        if (opener.globalList.stopsMarkers.length > 0) {
                                            opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop = opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].hour;
                                        }
                                    }
                                }
                            }
                        } else {
                            if ((opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].currentKm - opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].currentKm < opener.globalRoutes.mtsRoute) || (Routes.changeDirectionPosition(opener, opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].position, opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].position))) {
                                lstart = 0;
                                opener.globalRoutes.destination = opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].position;

                                opener.objMapControl.getDrivingRoute();
                                return;
                            }
                        }
                    }
                    if (lstart = 1) {
                        opener.globalRoutes.destination = opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint + 1].position;
                        opener.globalRoutes.lastOne = true;

                        if (opener.globalList.stopsMarkers.length > 0 && opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop == null) {
                            opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop = opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalRoutes.currentGpsPoint].hour;
                        }

                        setTimeout(opener.objMapControl.getDrivingRoute, 1000);
                    }
                    if (opener.globalList.stopsMarkers.length > 0) {
                        if (opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop == null) {
                            opener.globalList.stopsMarkers[opener.globalList.stopsMarkers.length - 1].finalTimeStop = "No definida, continúa hasta el siguiente día.";//opener.globalList.trackDataByImei[opener.globalRoutes.currentGpsPoint].hour;
                        }
                    }
                    drawDrivingRouteFinish();
                }


            }

            function drawDrivingRouteFinish() {
                clearInterval(opener.globalRoutes.refreshIntervalId);
                getBtnLoadRoute().value = "Cargar Ruta";
                getBtnLoadRoute().disabled = false;
                getBtnPlayPause().set_enabled(true);

                slider = getSliderRouter();
                slider.set_maximumValue(opener.globalBusStopsRouteHistory.trackDataByImei.length - 1);

                opener.globalRoutes.currentSlideRouteNumber = 0;

                if (opener.globalBusStopsRouteHistory.trackDataByImei.length > 0) {
                    var imei = opener.globalGPSImei.imeiSelected//getImeiValueTreeVehicleSelected();
                    var index = Routes.getIndexImei(opener.globalMasterPage.trackDataLastLocationList, imei);
                    if (index != -1) {
                        opener.objMapControl.setIconMarker(opener.objMapControl.GPSImeiRoute, opener.globalMasterPage.trackDataLastLocationList[index].image);
                    }

                    updateCurrentPositionRouteHistory(opener.globalRoutes.currentSlideRouteNumber);

                    slider.set_value(0);

                    getlbKmFinal().innerHTML = formatTwoDecimals(opener.globalBusStopsRouteHistory.trackDataByImei[opener.globalBusStopsRouteHistory.trackDataByImei.length - 1].currentKm) + " kms";
                    Routes.enableDisableSliderRoute(true, getSliderRouter());
                }
                else {
                    Routes.enableDisableSliderRoute(false, getSliderRouter());
                }
            }        

            function ckbSiNoCenterRouteChecked() {
                opener.globalRoutes.isCenterRoute = getCkbSiNoCenterRoute().checked;
            }

            function ckbSiNoCenterGPSImeiChecked() {
                opener.globalRoutes.isCenterGPSImei = getCkbSiNoCenterGPSImei().checked;
            }

            function updateSlideVisibleSpeed(sender, args) {

                var slideValue = sender.get_value();
                opener.globalBusStopsRouteHistory.speedRouteHistory = 1100 - (slideValue * 100);

                if (opener.globalBusStopsRouteHistory.slideInterval != null) {
                    window.clearInterval(opener.globalBusStopsRouteHistory.slideInterval);
                    opener.globalBusStopsRouteHistory.slideInterval = null;
                    opener.globalBusStopsRouteHistory.slideInterval = window.setInterval('selectNextSlideRoute()', opener.globalBusStopsRouteHistory.speedRouteHistory);
                }
            }

            function selectNextSlideRoute() {

                var slider = getSliderRouter();

                if (opener.globalBusStopsRouteHistory.currentSlideRouteNumber < opener.globalBusStopsRouteHistory.trackDataByImei.length) {
                    updateCurrentPositionRouteHistory(opener.globalBusStopsRouteHistory.currentSlideRouteNumber);
                }

                var slideNumber = opener.globalBusStopsRouteHistory.currentSlideRouteNumber + 1;
                if (slideNumber >= opener.globalBusStopsRouteHistory.trackDataByImei.length) {
                    //getBtnPlayPause().checked = !getBtnPlayPause().checked;
                    getBtnPlayPause().set_selectedToggleStateIndex(1);
                    getBtnPlayPause().set_checked(false);
                    stopSlideMovement();
                }
                else {
                    slider.set_value(slideNumber);
                }
            }

            function updateCurrentPositionRouteHistory(slideNumber) {
                opener.objMapControl.setPositionMarker(opener.globalBusStopsRouteHistory.GPSImeiRoute, opener.globalBusStopsRouteHistory.trackDataByImei[slideNumber].position);
                getlbKmActual().innerText = opener.globalBusStopsRouteHistory.trackDataByImei[slideNumber].totalKm + " / " + opener.globalBusStopsRouteHistory.totalKm + " kms";
                getlbKmTime().innerText = opener.globalBusStopsRouteHistory.trackDataByImei[slideNumber].hour;
                //opener.objMapControl.getDirectionFromPosition(opener.globalBusStopsRouteHistory.trackDataByImei[slideNumber].position);
                //getlbDirection().innerText = opener.globalBusStopsRouteHistory.trackDataByImei[slideNumber].direction;
                opener.objMapControl.getDirectionFromPositionBusHistory(opener.globalBusStopsRouteHistory.trackDataByImei[slideNumber].position, opener.globalBusStopsRouteHistory);
                //getlbDirection().innerText = opener.globalRoutes.direction;
                getlbDirection().innerText = opener.globalBusStopsRouteHistory.direction;
                getlbTrack().innerText = "Vueltas " + opener.globalBusStopsRouteHistory.trackDataByImei[slideNumber].totalTrack + " / " + opener.globalBusStopsRouteHistory.totalTrack;
                centerMapChecked(opener.globalBusStopsRouteHistory.trackDataByImei[slideNumber].position);
                getlbPeopleIn().innerText = "Personas que Entran " + opener.globalBusStopsRouteHistory.trackDataByImei[slideNumber].peopleTotalIn + " / " + opener.globalBusStopsRouteHistory.peopleTotalIn;
                getlbPeopleOut().innerText = "Personas que Salen " + opener.globalBusStopsRouteHistory.trackDataByImei[slideNumber].peopleTotalOut + " / " + opener.globalBusStopsRouteHistory.peopleTotalOut;
            }

            function centerMapChecked(location) {
                if (opener.globalRoutes.isCenterGPSImei) {
                    opener.objMapControl.centerMap(location);
                }
            }

            function updateSlideVisibleRoute(sender, args) {

                var slider = sender;

                updateSliderRoute(slider.get_value());

                if (opener.globalBusStopsRouteHistory.currentSlideRouteNumber < opener.globalBusStopsRouteHistory.trackDataByImei.length) {
                    updateCurrentPositionRouteHistory(opener.globalBusStopsRouteHistory.currentSlideRouteNumber);
                }
            }

            function updateSliderRoute(slideNumber) {
                opener.globalBusStopsRouteHistory.currentSlideRouteNumber = slideNumber;
            }

            function showHideHistoryRoute() {
                var ckbSiNoShowRoute = getCkbSiNoShowRoute();
                if (ckbSiNoShowRoute.checked) {
                    //Routes.showHistoryRoute(opener);
                }
                else {
                    //Routes.hideHistoryRoute(opener);
                }
            }

            function showOrhideStopsMarkers() {
                if (getCkbSiNoShowStops().checked) {
                    Routes.showStopsMarkers(opener);
                }
                else {
                    Routes.hideStopsMarkers(opener);
                }
            }

            function playStopSlideMovement(sender, args) {
                if (getBtnPlayPause().get_checked()) {
                    playSlideMovement();
                }
                else {
                    stopSlideMovement();
                }
                /*if (!args.get_checked()) {
                    playSlideMovement();
                }
                else {
                    stopSlideMovement();
                }*/
            }

            function playSlideMovement() {
                opener.globalBusStopsRouteHistory.slideInterval = window.setInterval('selectNextSlideRoute()', opener.globalBusStopsRouteHistory.speedRouteHistory);
            }

            function stopSlideMovement() {
                if (!opener.globalBusStopsRouteHistory.slideInterval) return;
                window.clearInterval(opener.globalBusStopsRouteHistory.slideInterval);
                opener.globalBusStopsRouteHistory.slideInterval = null;
            }

            function getlbDirection() {
                return $get('<%= lbDirection.ClientID %>');//.innerText;
            }

            function getlbPeopleIn() {
                return $get('<%= lbPeopleIn.ClientID %>');//.innerText;
            }

            function getlbPeopleOut() {
                return $get('<%= lbPeopleOut.ClientID %>');//.innerText;
            }

            function getCkbSiNoCenterGPSImei() {
                return $get('<%= ckbSiNoCenterGPSImei.ClientID %>');
            }

            function getrpvRoutesUpdateControl() {
                return "<%= rpvRoutes.ClientID %>";
            }

            function getBtnLoadRoute() {
                return $get('btnCargarRuta');
            }

            function getBtnPlayPause() {
                return $find('<%= btnPlayPause.ClientID %>');
            }

            function getSliderRouter() {
                return $find('<%= RadSliderRoute.ClientID %>');
            }

            function requestStart(object) {
                try {
                    $find("<%= RadAjaxLoadingPanel1.ClientID%>").show(object);
                }
                catch (e) {
                    null;
                }
            }

            function responseEnd(object) {
                //hide the loading panel and clean up the global variables 
                try {
                    $find("<%= RadAjaxLoadingPanel1.ClientID%>").hide(object);
                }
                catch (e) {
                    null;
                }
            }

            function getCkbSiNoShowRoute() {
                return $get('<%= ckbSiNoShowRoute.ClientID %>');
            }

            function getlbKmActual() {
                return $get('<%= lbKmActual.ClientID %>');//.innerText;
            }

            function getlbKmTime() {
                return $get('<%= lbTime.ClientID %>');//.innerText;
            }

            function getlbTrack() {
                return $get('<%= lbTrack.ClientID %>');//.innerText;
            }

            //Utilizada
            function getCkbZoomBusStops() {
                return $get('<%= ckbZoomBusStop.ClientID %>');
            }
            //Utilizada
            function getCkbCenterBusStops() {
                return $get('<%= ckbCenterBusStop.ClientID %>');
            }
        
            function resizeWindow(tab){
                if (tab == "Reproductor") {
                    opener.oWndShow.BusStopsRouteHistory.set_width("1020px");
                    opener.oWndShow.BusStopsRouteHistory.set_height("260px");
                }
                else {
                    opener.oWndShow.BusStopsRouteHistory.set_width("1250px");
                    opener.oWndShow.BusStopsRouteHistory.set_height("350px");
                }
            }

            function OnClientTabSelected(sender, eventArgs) {
                if (eventArgs != null) {
                    var tab = eventArgs.get_tab();
                    resizeWindow(tab.get_text());
                }
            }

    </script>
</telerik:RadScriptBlock>
<body onload="getCompaniesByAdminUsername()">
    <form id="form1" runat="server">
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server"  EnablePageMethods="true" EnablePartialRendering="true"></telerik:RadScriptManager>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
				<telerik:AjaxSetting AjaxControlID="AjaxControlID1">
					<UpdatedControls>
						<telerik:AjaxUpdatedControl ControlID="Loading" LoadingPanelID="RadAjaxLoadingPanel1" />
					</UpdatedControls>
				</telerik:AjaxSetting>
			</AjaxSettings>
        </telerik:RadAjaxManager>
        
        
        <telerik:RadTabStrip ID="rtsRoutes" runat="server" SelectedIndex="0" MultiPageID="rmpRoutes" OnClientTabSelected="OnClientTabSelected">
        <Tabs>
            <telerik:RadTab runat="server" Text="Rutas" PageViewID="rpvRoutes">
            </telerik:RadTab>
            <telerik:RadTab runat="server" Text="Reproductor" PageViewID="rpvPlayer">
            </telerik:RadTab>
        </Tabs>

        </telerik:RadTabStrip>
         
        <telerik:RadMultiPage ID="rmpRoutes" runat="server" SelectedIndex="0">
            <telerik:RadPageView ID="rpvRoutes" runat="server">
            <table>
                <tr>
                    <td>
					
                       
                                <fieldset>
							        <legend>Fecha Consulta</legend>
						                <telerik:RadCalendar ID="RadCalendar1" runat="server" CultureInfo="es-CR" EnableMultiSelect="false">
                                            <ClientEvents OnDateSelected="getVPCProcessByDateByCompanyID" />

						                </telerik:RadCalendar>
                            <asp:CheckBox ID="ckbZoomBusStop" runat="server" Text="Acercar Parada" Width="150px"/>
                            <asp:CheckBox ID="ckbCenterBusStop" runat="server" Text="Centrar Parada" Width="150px"/>
						        </fieldset>
                   
                 
          
                    </td>                   
                    <td>
                        <fieldset>
					            <legend>Compañias Registradas</legend>
					                <telerik:RadGrid ID="rgCompaniesGrid" runat="server" AllowMultiRowSelection="False" AutoGenerateColumns="False" CellSpacing="0" GridLines="None" Height="50px" OnNeedDataSource="rgCompaniesGrid_NeedDataSource" Skin="Metro" Width="100%">
						                <ClientSettings>
							                <Selecting AllowRowSelect="True" />
							                <ClientEvents OnRowClick="CompaniesGrid_OnRowClick" />
							                <Scrolling AllowScroll="True" UseStaticHeaders="False" />
						                </ClientSettings>
						                <MasterTableView ClientDataKeyNames="CompanyID" NoMasterRecordsText="No hay compañias registradas">
							                <CommandItemSettings ExportToPdfText="Export to PDF" />
							                <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
							                </RowIndicatorColumn>
							                <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
							                </ExpandCollapseColumn>
							                <Columns>
								                <telerik:GridBoundColumn DataField="CompanyID" FilterControlAltText="Filter Description column" HeaderText="ID" UniqueName="CompanyID" Visible="false">
								                </telerik:GridBoundColumn>
								                <telerik:GridBoundColumn DataField="Name" FilterControlAltText="Filter Description column" HeaderText="Nombre" Visible="true">
								                </telerik:GridBoundColumn>
							                </Columns>
							                <EditFormSettings>
								                <EditColumn FilterControlAltText="Filter EditCommandColumn column">
								                </EditColumn>
							                </EditFormSettings>
						                </MasterTableView>
						                <FilterMenu EnableImageSprites="true">
						                </FilterMenu>
					                </telerik:RadGrid>
				                </fieldset>
                    
            <fieldset>
            <legend>Información Registrada</legend>
            <telerik:RadGrid ID="VPCProcessGrid" runat="server" AutoGenerateColumns="False" CellSpacing="0" GridLines="None" Height="100px" Skin="Metro"  Width="850px" OnNeedDataSource="VPCProcessGrid_NeedDataSource">
                <ClientSettings>
                    <Selecting AllowRowSelect="True" />
                    <ClientEvents OnRowClick="VPCProcessGrid_OnRowClick" />
                    <Scrolling AllowScroll="True" UseStaticHeaders="False" />
                </ClientSettings>
                <MasterTableView NoMasterRecordsText="No hay registros encontrados" ClientDataKeyNames="NumControl, BusRouteID">
                    <CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>

                    <RowIndicatorColumn Visible="True" FilterControlAltText="Filter RowIndicator column">
                        <HeaderStyle Width="20px"></HeaderStyle>
                    </RowIndicatorColumn>

                    <ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column">
                        <HeaderStyle Width="20px"></HeaderStyle>
                    </ExpandCollapseColumn>

                    <Columns>
                        <telerik:GridBoundColumn DataField="NumControl" FilterControlAltText="Filter GPSUsername column" HeaderText="# Control" UniqueName="NumControl">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="DriverID" FilterControlAltText="Filter Name column" HeaderText="Conductor ID" UniqueName="DriverID" Visible="false">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="DriverName" FilterControlAltText="Filter FirstName column" HeaderText="Seudónimo" UniqueName="DriverName">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="GPSImei" FilterControlAltText="Filter LastName column" HeaderText="GPSImei" UniqueName="GPSImei">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="GPSImeiName" FilterControlAltText="Filter LastName column" HeaderText="Nombre GPSImei" UniqueName="GPSImeiName">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="BusRouteID" FilterControlAltText="Filter LastName column" HeaderText="Ruta ID" UniqueName="BusRouteID">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="BusRouteName" FilterControlAltText="Filter LastName column" HeaderText="Ruta" UniqueName="BusRouteName">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="Date" FilterControlAltText="Filter LastName column" HeaderText="Fecha" UniqueName="Date" Visible="false">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="TimeBegin" FilterControlAltText="Filter LastName column" HeaderText="Hora Desde" UniqueName="TimeBegin">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="TimeEnd" FilterControlAltText="Filter LastName column" HeaderText="Hora Hasta" UniqueName="TimeEnd">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="Status" FilterControlAltText="Filter LastName column" HeaderText="Estatus" UniqueName="Status">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="Process" FilterControlAltText="Filter LastName column" HeaderText="% Proceso" UniqueName="Process" Visible="false">
                        </telerik:GridBoundColumn>
                        <telerik:GridBoundColumn DataField="LastExecution" FilterControlAltText="Filter LastName column" HeaderText="Última Actualización" UniqueName="LastExecution" Visible="false">
                        </telerik:GridBoundColumn>
                    </Columns>

                    <EditFormSettings>
                        <EditColumn FilterControlAltText="Filter EditCommandColumn column"></EditColumn>
                    </EditFormSettings>

                    <PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>
                </MasterTableView>

                <PagerStyle PageSizeControlType="RadComboBox"></PagerStyle>

                <FilterMenu EnableImageSprites="False"></FilterMenu>
            </telerik:RadGrid> 
                </fieldset>
                    </td>
                </tr>
            </table>
                				            
            </telerik:RadPageView>
            <telerik:RadPageView ID="rpvPlayer" runat="server">
                <table class="auto-style2">
					<tr>
						<td>
							<table>
								<tr>
									<td>
										<fieldset>
											<legend>Configuración</legend>
											<div style="height:50px; width: 171px;">
											
											<asp:CheckBox ID="ckbSiNoCenterGPSImei" runat="server" Text="Centrar GPS" Checked="true" onclick="javascript:ckbSiNoCenterGPSImeiChecked()" />
											<br />
											<asp:CheckBox ID="ckbSiNoShowRoute" runat="server" onclick="javascript:showHideHistoryRoute()" Text="Mostrar ruta" Checked="true"/>
										</td>         
											</div>
										</fieldset>
									</td>
								</tr>
								<tr>
									<td>
										<div style="width: 171px;"></div>
									</td>
								</tr>
								<tr>
									<td>
										<fieldset>
											<legend>Velocidad</legend>
											<telerik:RadSlider ID="RadSliderSpeed" runat="server" Height="20px" ItemType="None" MaximumValue="11" MinimumValue="1" OnClientLoad="updateSlideVisibleSpeed" OnClientValueChanged="updateSlideVisibleSpeed" TrackPosition="Center" Value="1" Width="150px">
											</telerik:RadSlider>
										</fieldset>
									</td>
								</tr>
							</table>
                                                                    
						</td>
						<td>
							<fieldset>
								<legend>Paso 2. Reproducir ruta</legend>
								<table class="auto-style2" style="text-align: center; vertical-align: top;">
									<tr>
                                                                            
										<td>
											<asp:Label ID="lbKmActual" runat="server" style="text-align: center" Text="0.0 Km" Width="120px"></asp:Label>
										</td>
										<td colspan="3">
											<telerik:RadSlider ID="RadSliderRoute" runat="server" Height="40px" ItemType="Tick" MaximumValue="120" OnClientLoad="updateSlideVisibleRoute" OnClientValueChanged="updateSlideVisibleRoute" TrackPosition="Center" Value="0" Width="600px">
											</telerik:RadSlider>
										</td>

									</tr>
									<tr>
										<td>
                                            <asp:Label ID="lbTrack" runat="server" style="text-align: center" Text="Vueltas ? / ?" Width="120px"></asp:Label>
                                                                            
										</td>
										<td colspan="3">
                                            <asp:Label ID="lbDirection" runat="server" style="text-align: center" Text="Dirección" Width="600px"></asp:Label>
										</td>
									</tr>
									<tr>
										<td>
											<asp:Label ID="lbTime" runat="server" style="text-align: center" Text="Fecha" Width="120px"></asp:Label>
										</td>
                                        <td>
											<asp:Label ID="lbPeopleIn" runat="server" style="text-align: center" Text="Personas Entran ? / ?" Width="200px"></asp:Label>
										</td>
										<td>
											<telerik:RadButton ID="btnPlayPause" runat="server" ButtonType="ToggleButton" Checked="false" Height="32px" OnClientCheckedChanged="playStopSlideMovement" ToggleType="CheckBox" Width="32px" AutoPostBack="False" Enabled="False">
												<ToggleStates>
													<telerik:RadButtonToggleState ImageUrl="../Template/Icons/32px/Button-Play-icon.png" Text="Play" />
													<telerik:RadButtonToggleState ImageUrl="../Template/Icons/32px/Button-Pause-icon.png" Selected="true" Text="Pause" />
												</ToggleStates>
											</telerik:RadButton>
										</td>
                                        <td>
											<asp:Label ID="lbPeopleOut" runat="server" style="text-align: center" Text="Personas Salen ? / ?" Width="200px"></asp:Label>
										</td>
									</tr>
								</table>
                                                                            
							</fieldset>
                                                                        
						</td>
					</tr>
				</table>
            </telerik:RadPageView>
        </telerik:RadMultiPage>

        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default"></telerik:RadAjaxLoadingPanel>
    </form>
</body>
</html>
